﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using PicStore.BLL.Interface;
using PicStore.Model;
using PicStore.Web.Lib;
using PicStore.Web.Models.Picture;

namespace PicStore.Web.Controllers
{
    [Authorize]
    public class PictureController : BaseController
    {
        [Dependency]
        public IPictureService PictureService { get; set; }

        [Dependency]
        public ICategoryService CategoryService { get; set; }

        [Dependency]
        public IRequestService RequestService { get; set; }

        public ActionResult Index()
        {
            return View();
        }

        #region methods to get filters
        public ActionResult GetPlaceValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Place), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetSexValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Sex), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetItemValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Item), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetColorValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Color), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetStyleValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Style), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetLengthValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Length), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetCollarValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Collar), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetFrontValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Front), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetSleeveValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Sleeve), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetSweaterTextureValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.SweaterTexture), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetTypeValues()
        {
            return Json(GetCategoryItems((int)BaseCategoryEnum.Type), JsonRequestBehavior.AllowGet);
        }
        #endregion

        private List<CategoryItemModel> GetCategoryItems(int categoryId)
        {
            var itemList = CategoryService.GetItemsByCategoryId(categoryId);

            List<CategoryItemModel> resultList = new List<CategoryItemModel>();
            foreach (var item in itemList)
            {
                CategoryItemModel itemInfo = new CategoryItemModel();
                itemInfo.ItemName = item.ItemName;
                itemInfo.ItemValue = item.ItemValue;

                resultList.Add(itemInfo);
            }
            return resultList;
        }

        public ActionResult GetPictures(DateTime fromDate, DateTime toDate, string orderBy, int pageIndex = 1, bool isAsc = true)
        {
            string keyTosearch = string.Empty;
            //if (string.IsNullOrEmpty(name) == false)
            //{
            //    keyTosearch = name;
            //}
            int count = 0;
            int totalPages = 0;
            string[] array = new string[] { };
            List<PictureInfo> pictures = PictureService.GetPictureList(CurrentUser.UserId, fromDate, toDate,
                orderBy, out count, out totalPages, PageSize, pageIndex, isAsc);
            List<PictureModel> list = GetPictureModel(pictures);

            return Json(new { Data = list.ToArray(), TotalPages = totalPages }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetPicturesWithFilter(DateTime fromDate, DateTime toDate, string orderBy,
            string places, string sexs, string items, string colors, string styles, string lengths, string collars, string fronts,
            string sleeves, string sweaterTextures, string types, int pageIndex = 1, bool isAsc = true)
        {
            int count = 0;
            int totalPages = 0;
            List<string> placeArray = Convertor.ConverToStringArray(places);
            List<string> sexsArray = Convertor.ConverToStringArray(sexs);
            List<string> itemsArray = Convertor.ConverToStringArray(items);
            List<string> colorsArray = Convertor.ConverToStringArray(colors);
            List<string> collarsArray = Convertor.ConverToStringArray(collars);
            List<string> stylesArray = Convertor.ConverToStringArray(styles);
            List<string> lengthsArray = Convertor.ConverToStringArray(lengths);
            List<string> frontsArray = Convertor.ConverToStringArray(fronts);
            List<string> sleevesArray = Convertor.ConverToStringArray(sleeves);
            List<string> sweaterTexturesArray = Convertor.ConverToStringArray(sweaterTextures);
            List<string> typesArray = Convertor.ConverToStringArray(types);
            // combine the filter into array.
            List<PictureInfo> pictures = PictureService.GetPictureList(CurrentUser.UserId, fromDate, toDate, placeArray, sexsArray,
                itemsArray, colorsArray, stylesArray, lengthsArray, collarsArray, frontsArray, sleevesArray, sweaterTexturesArray,
                typesArray, orderBy, out count, out totalPages, PageSize, pageIndex, isAsc);

            List<PictureModel> list = GetPictureModel(pictures);

            return Json(new { Data = list.ToArray(), TotalPages = totalPages }, JsonRequestBehavior.AllowGet);
        }

        private List<PictureModel> GetPictureModel(List<PictureInfo> pictures)
        {
            List<PictureModel> list = new List<PictureModel>();
            foreach (var pic in pictures)
            {
                var picture = GetPictureModel(pic);

                list.Add(picture);
            }

            return list;
        }

        private PictureModel GetPictureModel(PictureInfo pic)
        {
            string pictureDomain = ConfigurationManager.AppSettings["PictureDomain"];
            var picture = new PictureModel()
                {
                    Id = pic.Id,
                    PicturePath = pictureDomain + pic.RelativePictureName,
                    PictureName = pic.PictureOnlyFileName,
                    SmallPicPath = pictureDomain + pic.RelativePictureName,
                    Place = CategoryService.GetItemName((int) BaseCategoryEnum.Place, pic.Place),
                    Sex = CategoryService.GetItemName((int) BaseCategoryEnum.Sex, pic.Sex),
                    Item = CategoryService.GetItemName((int) BaseCategoryEnum.Item, pic.Item),
                    Color = CategoryService.GetItemName((int) BaseCategoryEnum.Color, pic.Color),
                    Style = CategoryService.GetItemName((int) BaseCategoryEnum.Style, pic.Style),
                    Length = CategoryService.GetItemName((int) BaseCategoryEnum.Length, pic.Length),
                    Collar = CategoryService.GetItemName((int) BaseCategoryEnum.Collar, pic.Collar),
                    Front = CategoryService.GetItemName((int) BaseCategoryEnum.Front, pic.Front),
                    Sleeve = CategoryService.GetItemName((int) BaseCategoryEnum.Sleeve, pic.Sleeve),
                    SweaterTexture = CategoryService.GetItemName((int) BaseCategoryEnum.SweaterTexture, pic.SweaterTexture),
                    Type = CategoryService.GetItemName((int)BaseCategoryEnum.Type, pic.Type),
                    Date = pic.TakePhotoDate.ToShortDateString(),
                    CreaterName = pic.CreaterName,
                    OperatorName = pic.OperatorName,
                };
            return picture;
        }

        private List<SelectListItem> GetCategoryItemList(BaseCategoryEnum baseCategory, string selectedValue)
        {
            var itemList = GetCategoryItems((int)baseCategory);
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (var category in itemList)
            {
                SelectListItem item = new SelectListItem
                {
                    Text = category.ItemName,
                    Value = category.ItemValue.ToString(),
                };
                if (category.ItemValue == selectedValue)
                {
                    item.Selected = true;
                }
                list.Add(item);
            }
            return list;
        }

        private EditPictureModel InitialEditPictureModel(PictureInfo picture)
        {
            var model = EditPictureModel.BuildPictureModel(picture);
            model.PlaceList = GetCategoryItemList(BaseCategoryEnum.Place, picture.Place);
            model.SexList = GetCategoryItemList(BaseCategoryEnum.Sex, picture.Sex);
            model.ItemList = GetCategoryItemList(BaseCategoryEnum.Item, picture.Item);
            model.ColorList = GetCategoryItemList(BaseCategoryEnum.Color, picture.Color);
            model.StyleList = GetCategoryItemList(BaseCategoryEnum.Style, picture.Style);
            model.LengthList = GetCategoryItemList(BaseCategoryEnum.Length, picture.Length);
            model.CollarList = GetCategoryItemList(BaseCategoryEnum.Collar, picture.Collar);
            model.FrontList = GetCategoryItemList(BaseCategoryEnum.Front, picture.Front);
            model.SleeveList = GetCategoryItemList(BaseCategoryEnum.Sleeve, picture.Sleeve);
            model.SweaterTextureList = GetCategoryItemList(BaseCategoryEnum.SweaterTexture, picture.SweaterTexture);
            model.TypeList = GetCategoryItemList(BaseCategoryEnum.Type, picture.Type);

            return model;
        }

        public ActionResult Update(int id)
        {
            ViewBag.Action = "Update";
            ViewBag.OnSuccess = "viewModel.onDataUpdated";
            var picture = PictureService.GetPictureById(id);
            var model = InitialEditPictureModel(picture);
            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Update(EditPictureModel picture)
        {
            PictureService.UpdatePicture(CurrentUser.UserId, picture.Id, picture.Place, picture.Sex, picture.Item, picture.Color, 
                picture.Style, picture.Length, picture.Collar, picture.Front, picture.Sleeve, picture.SweaterTexture, picture.Type);
            var pictureInfo = PictureService.GetPictureById(picture.Id);
            return Json(GetPictureModel(pictureInfo));
        }

        public ActionResult Detail(int id)
        {
            ViewBag.Action = "";
            ViewBag.OnSuccess = "viewModel.onDataViewed";

            var picture = PictureService.GetPictureById(id);
            var model = GetPictureModel(picture);
            return View("Detail", model);
        }

        public ActionResult Delete(int id)
        {
            var picture = PictureService.GetPictureById(id);
            PictureService.DeletePictureById(id);
            return Json(GetPictureModel(picture), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DownloadExcel(DateTime fromDate, DateTime toDate, bool needDownloadPicture)
        {
            List<PictureInfoForExcel> pictures = PictureService.GetPictureListForExcel(CurrentUser.UserId, fromDate, toDate);
            return DownloadExcelWithList(needDownloadPicture, pictures);
        }

        private ActionResult DownloadExcelWithList(bool needDownloadPicture, List<PictureInfoForExcel> pictures)
        {
            if (pictures == null)
            {
                return Json(new {path = string.Empty, success = false, error = "There is no pictures to download."},
                            JsonRequestBehavior.AllowGet);
            }
            string error;
            string zipFileUrl;
            var getZipFileSuccess = new PictureHelper().DownloadExcelWithPictures(needDownloadPicture, pictures, out error, out zipFileUrl);

            return Json(new {path = zipFileUrl, success = getZipFileSuccess, error = error}, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DownloadExcelWithFilters(DateTime fromDate, DateTime toDate, bool needDownloadPicture, string places, string sexs, 
            string items, string colors, string styles, string lengths, string collars, string fronts, string sleeves, string sweaterTextures, string types)
        {
            List<string> placeArray = Convertor.ConverToStringArray(places);
            List<string> sexsArray = Convertor.ConverToStringArray(sexs);
            List<string> itemsArray = Convertor.ConverToStringArray(items);
            List<string> colorsArray = Convertor.ConverToStringArray(colors);
            List<string> collarsArray = Convertor.ConverToStringArray(collars);
            List<string> stylesArray = Convertor.ConverToStringArray(styles);
            List<string> lengthsArray = Convertor.ConverToStringArray(lengths);
            List<string> frontsArray = Convertor.ConverToStringArray(fronts);
            List<string> sleevesArray = Convertor.ConverToStringArray(sleeves);
            List<string> sweaterTexturesArray = Convertor.ConverToStringArray(sweaterTextures);
            List<string> typesArray = Convertor.ConverToStringArray(types);

            List<PictureInfoForExcel> pictures = PictureService.GetPictureListForExcelWithFilters(CurrentUser.UserId,
                fromDate, toDate, placeArray, sexsArray, itemsArray, colorsArray, stylesArray, lengthsArray, collarsArray,
                frontsArray, sleevesArray, sweaterTexturesArray, typesArray);

            return DownloadExcelWithList(needDownloadPicture, pictures);
        }

        public ActionResult ApplyRequest(DateTime fromDate, DateTime toDate, bool needDownloadPicture, bool needDetailFilters, string places, string sexs, 
            string items, string colors, string styles, string lengths, string collars, string fronts, string sleeves, string sweaterTextures)
        {
            //string error = string.Empty;

            //bool isSuccess = RequestService.SaveDownloadRequest(CurrentUser.UserId, fromDate, toDate, needDownloadPicture, 
            //    needDetailFilters, places, sexs, items, colors, styles, lengths, collars, fronts, sleeves, sweaterTextures, out error);

            //return Json(new { success = isSuccess, error = error }, JsonRequestBehavior.AllowGet);
            return null;
        }
    }
}
